<?php
require_once('../dao/database.php');
require_once('../dao/user_db.php');
require_once('../domain/User.php');
require_once("../util/Validation.php");
require_once('../util/Util.php'); 
require_once("../email/MailService.php");

// Get the action to perform
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else if (isset($_GET['action'])) {
    $action = $_GET['action'];
} else {
    $action = 'show_home';
}

$reset_message = '';

if (isset($_POST['submit'])) {   
    // Perform the specified action
    switch ($action) {
        case 'reset':
            if (isset($_POST['nickname']) || $_POST['email']) {
                //get value vom user
                $val = new Validation();
                $nickname = $val->validateRequiredString('nickname', "Der Username ist ein Pflichtfeld.");
                $email = $val->validateRequiredString('email', "Die E-Mailadresse ist ein Pflichtfeld.");

                //search in user in db
                $users = findUserByNicknameAndEmail($nickname,$email);

                if (count($users) == 1) {
                    $newPassword  = Util::randomString(8);
                    $newPasswordHash = hash( 'sha256', $newPassword );

                    //update in DB
                    update_user_password($users[0], $newPasswordHash);

                    //send Email
                    try {
                        $mailService = new MailService();
                        $mailService->sendPasswordResetEmail($email, $nickname, $newPassword);
                    } catch (Exception $e) {
                        $error_message = 'Es tratt ein Fehler beim Versenden der Registrierungs E-Mail auf!';
                        include('../errors/error.php');
                        exit();
                    }
                    $reset_message = 'Ihr neues Passwort wurde Ihnen per E-Mail zugesendet.';
                    
                    //reset Values
                    $nickname = '';
                    $email = '';

                    //header('Location: ../main/index.php');
                    include('resetpwView.php');
                    
                } else {
                    if(count($users) == 0){
                        $reset_message = 'Die Kombination Benutzername und E-Mail Adresse ist nicht vorhanden.';
                        include('resetpwView.php');
                    } else {
                        $error_message = 'Interner Fehler: Errorcode 0002';
                        include('../errors/error.php');
                    }
                    exit();
                }
            } else {
                $reset_message = '';
                include('loginView.php');
            }
            break;
        case 'show_home':
            include('homeView.php');
            break;
    } 
} else {
        $reset_message = '';
        include('resetpwView.php');
} 
